from celery import Celery
import random
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Computer.settings')
django.setup()
# 位置很重要
from goods.models import IndexPromote, GoodsBanner, Goods, GoodsType

app = Celery('celery_tasks.task', broker='redis://127.0.0.1:6379/5')


@app.task
def send_active_mail(to_user, token=''):
    print(to_user)
    '''发送激活邮件and 修改密码'''
    subject = '电脑牌电脑用户密码重置页'
    message = ''
    sender = '1785662113@qq.com'
    recever = [to_user]
    new_str = ''
    # 指明这是html格式的链接
    if token == '':
        str = '1234567890qwertyuiopasdfhgklzxcvbnm'
        for i in range(4):
            new_str += str[random.randint(0, len(str))]

    html_message = '<h1>亲爱的%s用户欢迎来到电脑牌电脑密码重置页，您的密钥为%s' % (to_user, new_str)

    if token != '':
        recever = [to_user.email]
        subject = '电脑牌电脑用户激活链接'
        html_message = '<h1>%s欢迎来到电脑牌电脑激活页，点击激活即可登录</h1></br><a href="http://127.0.0.1:8000/computer/user/active/%s">点击激活</a>' % (to_user.username, token)

    send_mail(subject, message, sender, recever, html_message=html_message)
    if token == '':
        return new_str


@app.task
def static_index():
    # 促销
    promote = IndexPromote.objects.all().order_by('id')
    # 轮播
    slider = GoodsBanner.objects.all().order_by('-id')

    # 精品推荐
    recommend = Goods.objects.all().order_by('-id')[:6]

    # 笔记本/游戏本
    laptop = GoodsType.objects.get(name='笔记本') # 注意用get
    laptop = laptop.goods_set.all().order_by('-id')[:6]

    # Desktop
    desktop = GoodsType.objects.get(name='台式机').goods_set.all().order_by('-id')[:6]

    # 配件
    parts = GoodsType.objects.get(name='配件').goods_set.all()[:3]

    context = {'promote': promote,
               'slider': slider,
               'recommend': recommend,
               'laptop': laptop,
               'desktop': desktop,
               'parts': parts
               }

    # 使用模版
    temp = loader.get_template('index_static.html')
    index_static_html = temp.render(context)
    # 生成首页对应的静态文件
    save_path = os.path.join(settings.BASE_DIR, 'static/index.html')
    with open(save_path, 'w') as f:
        f.write(index_static_html)

